package com.cn.ZhiKeDianShang.ui.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.ZhiKeDianShang.AppConfig;
import com.cn.ZhiKeDianShang.R;
import com.cn.ZhiKeDianShang.base.BaseActivity;
import com.cn.ZhiKeDianShang.model.TaskInfoBean;
import com.cn.ZhiKeDianShang.model.ViewpagerBean;
import com.cn.ZhiKeDianShang.model.event.refushBean;
import com.cn.ZhiKeDianShang.model.event.sendImageBean;
import com.cn.ZhiKeDianShang.model.response.UserInfoBean;
import com.cn.ZhiKeDianShang.presenter.LoginUserPresenter;
import com.cn.ZhiKeDianShang.presenter.view.LoginUserView;
import com.cn.ZhiKeDianShang.ui.fragment.OrderDetailsFragment;
import com.cn.ZhiKeDianShang.ui.fragment.SubmitFreagment;
import com.cn.ZhiKeDianShang.util.BitmapUtil;
import com.cn.ZhiKeDianShang.util.CommontDialog;
import com.cn.ZhiKeDianShang.util.KeyBoardUtil;
import com.cn.ZhiKeDianShang.util.ToastUtil;
import com.cn.ZhiKeDianShang.util.view.MyTabLayout;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.HttpUtils;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.ObjectResult;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.Result;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.compress.FileUtil;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhihu.matisse.internal.ui.widget.CropImageView;
import com.zhihu.matisse.listener.OnSelectedListener;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import id.zelory.compressor.Compressor;
import io.reactivex.functions.Consumer;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/7/3.
 * do what to 2017/7/3
 */

public class OrderDetailActivity extends BaseActivity<LoginUserView, LoginUserPresenter> implements LoginUserView {

    @BindView(R.id.setting_back)
    ImageView settingBack;
    @BindView(R.id.tl_tabs)
    MyTabLayout tlTabs;
    @BindView(R.id.vp_conViewPagertent)
    ViewPager vpConViewPagertent;


    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_delete_task)
    TextView tv_delete_task;


    @BindView(R.id.rl_appbarlayout)
    RelativeLayout rlAppbarlayout;


    //區別是哪个OrderDetailsFragment界面 传过来要上传图片操作
    String mOrderId;
    //    任务ID
    String taskid = "";
    //在今日任务过来   还是历史任务过来  这个当取消认为 以后要传回去，以这个参数来判断 今日任务页面刷新还是历史任务页面刷新
    int type;
    int sumNumber = 6;

    @Override
    protected int getNormalLayoutId() {
        return R.layout.activity_orderdetail_activity;
    }

    @Override
    protected int getErrorLayoutId() {
        return R.layout.activity_orderdetail_activity;
    }

    @Override
    protected LoginUserPresenter createPresenter() {
        return new LoginUserPresenter(this, this);
    }


    @Override
    protected void initViewsAndEvents() {
        //不允许左滑返回
        mSwipeBackLayout.setEnableGesture(false);
        if (getIntent() != null) {
            taskid = getIntent().getStringExtra("taskid");
            type = getIntent().getIntExtra("type", 0);
            Log.d("Debug", "传过来的type值为" + type);
        }
        getTaskinfo();
    }

    Boolean isTaskDelete = false;
    String orderId = "";

    /**
     * @param
     */
    private void getTaskinfo() {
        Map<String, String> params = new HashMap<>();
        params.put("taskid", taskid);
        HttpUtils.post().url(AppConfig.ORDER_TASKINFO)
                .params(params)
                .addSecret()
                .build()
                .execute(new BaseCallback<TaskInfoBean>(TaskInfoBean.class) {
                    @Override
                    public void onResponse(ObjectResult<TaskInfoBean> result) {
                        try {
                            Log.d("Debug", "到达请求这里---");
                            if (Result.checkSuccess(OrderDetailActivity.this, result)) {

                                ArrayList<ViewpagerBean> titleDatas = new ArrayList<>();
                                ArrayList<Fragment> fragmentList = new ArrayList<Fragment>();
                                TaskInfoBean data = result.getData();

                                if (data.getTaskinfo().getStatus() == 2) {
                                    tv_delete_task.setVisibility(View.VISIBLE);
                                } else {
                                    tv_delete_task.setVisibility(View.GONE);
                                }

                                List<TaskInfoBean.OrderinfoBean> orderinfo = data.getOrderinfo();
                                for (int i = 0; i < orderinfo.size(); i++) {
                                    TaskInfoBean.OrderinfoBean orderinfoBean = orderinfo.get(i);
                                    titleDatas.add(new ViewpagerBean("单" + (i + 1), orderinfoBean.getId() + ""));
                                    fragmentList.add(OrderDetailsFragment.getInstance(orderinfoBean.getId() + "", data.getTaskinfo().getStatus() + "", orderinfo.get(i), new showPhotoPop() {
                                        @Override
                                        public void showPhotoPop(String orderId, int canSelectNumber) {
                                            mOrderId = orderId;
                                            initPermission(canSelectNumber);
                                        }
                                    }));
                                }

                                if (orderinfo.size() > 0) {
                                    tvTitle.setText(titleDatas.get(0).getTitleName());
                                    orderId = orderinfo.get(0).getId() + "";
                                }

                                titleDatas.add(new ViewpagerBean("提交", data.getTaskinfo().getId() + ""));
                                fragmentList.add(SubmitFreagment.getInstance(data.getTaskinfo().getId() + "", data.getTaskinfo(), new showPhotoPop() {
                                    @Override
                                    public void showPhotoPop(String taskId, int canSelectNumber) {
                                        mOrderId = taskId;
                                        initPermission(canSelectNumber);
                                    }
                                }));

                                MyViewPageAdapter myViewPageAdapter = new MyViewPageAdapter(getSupportFragmentManager(), titleDatas, fragmentList);
                                vpConViewPagertent.setAdapter(myViewPageAdapter);

                                vpConViewPagertent.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                                    @Override
                                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                                    }

                                    @Override
                                    public void onPageSelected(int position) {
                                        tvTitle.setText(titleDatas.get(position).getTitleName());
                                        if (titleDatas.get(position).getItemName().equals("提交")) {
                                            isTaskDelete = true;
                                            tv_delete_task.setText("取消任务");
                                        } else {
                                            isTaskDelete = false;
                                            tv_delete_task.setText("取消订单");
                                            orderId = orderinfo.get(position).getId() + "";
                                        }
                                        if (data.getTaskinfo().getStatus() == 2) {
                                            tv_delete_task.setVisibility(View.VISIBLE);
                                        } else {
                                            tv_delete_task.setVisibility(View.GONE);
                                        }

                                        KeyBoardUtil.hindKeyBoard(OrderDetailActivity.this);

                                    }

                                    @Override
                                    public void onPageScrollStateChanged(int state) {

                                    }
                                });

                                tlTabs.setupWithViewPager(vpConViewPagertent);
                                tlTabs.setTabsFromPagerAdapter(myViewPageAdapter);

                            }


                        } catch (Exception e) {


                        }
//                     DialogHelper.dismissProgressDialog();

                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    @Override
    public void onLogin(UserInfoBean resultBean) {

    }

    @Override
    public void requestFailed(String message) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    AlertDialog alertDialog;

    @OnClick({R.id.setting_back, R.id.tv_delete_task})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.setting_back:
                finish();
                break;
            case R.id.tv_delete_task:
                String text = "";
                if (isTaskDelete) {
                    text = "请输入取消任务原因";
                } else {
                    text = "请输入取消订单原因";
                }
                //删除订单操作
                String finalText = text;
                alertDialog = CommontDialog.cacleTask(OrderDetailActivity.this, finalText, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        EditText et_number = (EditText) alertDialog.findViewById(R.id.et_number);
                        if (et_number.getText().toString().length() == 0) {
                            ToastUtil.showShort(finalText);
                            return;
                        }
                        cancaleTask(isTaskDelete, et_number.getText().toString());
                    }
                });
                break;
        }
    }


    /**
     * 取消订单
     */
    private void cancaleTask(boolean isTaskDelete, String cancelreason) {
        Map<String, String> params = new HashMap<>();
        String url = "";
        if (isTaskDelete) {
            params.put("taskid", taskid);
            url = AppConfig.ORDER_CANCLETASK;
            Log.d("Debug", "调用的接口" + url + "taskid" + taskid);
        } else {
            params.put("orderid", orderId);
            url = AppConfig.ORDER_CANCLEORDER;
            Log.d("Debug", "调用的接口" + url + "orderId" + orderId);
        }

        params.put("cancelreason", cancelreason);
        HttpUtils.post().url(url)
                .params(params)
                .addSecret()
                .build()
                .execute(new BaseCallback<TaskInfoBean>(TaskInfoBean.class) {
                    @Override
                    public void onResponse(ObjectResult<TaskInfoBean> result) {
//                        DialogHelper.dismissProgressDialog();
                        Log.d("Debug", "到达请求这里---");
                        if (result.getResultCode() == 1) {
                            alertDialog.dismiss();
                            EventBus.getDefault().post(new refushBean(type));
                            ToastUtil.showShort(result.getResultMsg());
                            finish();
                        } else {
                            ToastUtil.showShort(result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    public class MyViewPageAdapter extends FragmentPagerAdapter {
        private ArrayList<ViewpagerBean> titleList;
        private ArrayList<Fragment> fragmentList;

        public MyViewPageAdapter(FragmentManager fm, ArrayList<ViewpagerBean> titleList, ArrayList<Fragment> fragmentList) {
            super(fm);
            this.titleList = titleList;
            this.fragmentList = fragmentList;
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titleList.get(position).getItemName();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public interface showPhotoPop {
        void showPhotoPop(String orderId, int canSelectNumber);
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    /**
     * SD卡根目录
     */
    private final String externalStorageDirectory = Environment.getExternalStorageDirectory().getPath() + "/picture/";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("Debug", "到达回调这里");
        super.onActivityResult(requestCode, resultCode, data);
        ArrayList<String> compressinPath = new ArrayList<>();
        if (requestCode == 1000 && resultCode == RESULT_OK) {
            this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    compressinPath.clear();
                    //没压缩之前的文件
                    List<String> originalPath = Matisse.obtainPathResult(data);
                    for (int i = 0; i < originalPath.size(); i++) {
                        //获得没压缩的文件
                        Log.d("Debug", "返回的图片大小为");
                        try {
                            File file = FileUtil.getFileByPath(Matisse.obtainPathResult(data).get(i));
                            long fileSize = getFileSize(file);
                            Log.d("Debug", "返回的图片数据大小" + fileSize / 1024 + "kb");
                            //图片大于200k 压缩操作
                            if (fileSize / 1024 > 200) {
                                //这个是下面Compressor 失败之后备用的上传图片地址 只有一张图片的时候（因为相册选择没有问题，拍照有问题的，所以判断为1张的时候，不论拍照还是相册选择都进行备用图片获得）
                                String CompressorFailpath = "";
                                if (originalPath.size() == 1) {
                                    CompressorFailpath = BitmapUtil.compressImage(file.getPath());
                                }
                                //大于1m  采样率压缩
                                if (fileSize / 1024 / 1024 > 1) {
                                    file = BitmapUtil.compressImageReturnFile(file.getPath(), 100, 2);
                                }
                                Log.d("Debug", "另外一种压缩方式的地址为------------" + getFileSize(file) / 1024);
                                try {
                                    File compressedImage = new Compressor(OrderDetailActivity.this)
                                            .setMaxWidth(640)
                                            .setMaxHeight(480)
                                            .setQuality(90)
                                            .setCompressFormat(Bitmap.CompressFormat.JPEG)
                                            .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                                                    Environment.DIRECTORY_PICTURES).getAbsolutePath())
                                            .compressToFile(file);
                                    Log.d("Debug", "另外一种压缩方式的地址为" + compressedImage.getPath());
                                    compressinPath.add(compressedImage.getPath() + "");
                                } catch (Exception e) {
                                    //部分手机Compressor 不成功 用上面的CompressorFailpath备用的地址
                                    compressinPath.add(CompressorFailpath + "");
                                }
                            } else {
                                compressinPath.add(file.getPath() + "");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                    EventBus.getDefault().postSticky(new sendImageBean(mOrderId, compressinPath));
                }
            });
        }


    }


    /**
     * 获取指定文件大小
     */
    public long getFileSize(File file) throws Exception {
        long size = 0;
        if (file.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(file);
            size = fis.available();
        } else {
            Log.e("获取文件大小", "文件不存在!");
        }
        return size;
    }

    private void initPermission(int canSelectNumber) {
        RxPermissions rxPermissions = new RxPermissions(this);

        rxPermissions.request(
                Manifest.permission.CAMERA
                , Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.READ_EXTERNAL_STORAGE
        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    //申请的权限全部允许
//                    Toast.makeText(OrderDetailActivity.this, "允许了权限!", Toast.LENGTH_SHORT).show();
                    Matisse.from(OrderDetailActivity.this)
                            .choose(MimeType.ofImage(), false)
                            .showSingleMediaType(true)
                            .countable(true)
                            .capture(true)
                            .isCrop(false)
                            .captureStrategy(
                                    new CaptureStrategy(true, "com.cn.ZhiKeDianShang"))
                            .maxSelectable(canSelectNumber)
                            .isCrop(false)
                            .cropStyle(CropImageView.Style.CIRCLE)
                            .isCropSaveRectangle(false)
                            .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                            .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                            .originalEnable(true)
                            .maxOriginalSize(10)
                            .thumbnailScale(0.85f)
                            .imageEngine(new GlideEngine())
                            .setOnSelectedListener(new OnSelectedListener() {
                                @Override
                                public void onSelected(@NonNull List<Uri> uriList, @NonNull List<String> pathList) {
                                    if (uriList != null && uriList.size() > 0 && pathList != null && pathList.size() > 0) {
                                        Log.d("Leo", uriList.size() + " " + uriList.get(0) + " " + pathList.size() + " " + pathList.get(0));
                                    }
                                }
                            })
                            .forResult(1000);
                } else {
                    //只要有一个权限被拒绝，就会执行
                    Toast.makeText(OrderDetailActivity.this, "未授权权限，部分功能不能使用", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


}
